<template>
	<view class="content">
		<!-- 聊天内容 -->
		<scroll-view class="chat" scroll-y="true" scroll-with-animation="true" :scroll-into-view="scrollToView">
			<view class="chat-main" :style="{paddingBottom:inputh+'px'}">
				<view class="chat-ls" v-for="(item,index) in unshiftmsg" :key="index" :id="'msg'+ index">
					<view class="chat-time" v-if="item.date != ''">{{changeTime(item.date)}}</view>
					<view class="msg-m msg-left" v-if="item.fromId ==  friendName">
						<!-- <image class="user-img" src="/static/defaultAvatar.png"></image> -->
						<view style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
							<image class="user-img" src="/static/defaultAvatar.png"></image>
							<text class="user-name">{{item.fromName}}</text>
						</view>
						<view class="message" v-if="item.messageType == 0">
							<!-- 文字 -->
							<view class="msg-text">{{item.messageData}}</view>
						</view>
						<view class="message" v-if="item.messageType == 1" @tap="previewImg(item.messageData)">
							<!-- 图像 -->
							<image :src="item.messageData" class="msg-img" mode="widthFix"></image>
						</view>
					</view>
					<view class="msg-m msg-right" v-if="item.fromId != friendName">
						<view style="display: flex;flex-direction: column;justify-content: center; align-items: center;">
							<image class="user-img" src="/static/defaultAvatar.png"></image>
							<text class="user-name">{{userName}}</text>
						</view>
						<view class="message" v-if="item.messageType == 0">
							<view class="msg-text">{{item.messageData}}</view>
						</view>
						<view class="message" v-if="item.messageType == 1" @tap="previewImg(item.messageData)">
							<image :src="item.messageData" class="msg-img" mode="widthFix"></image>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<submit @inputs="inputs" @heights="heights"></submit>
	</view>
</template>

<script>
	import dateTime from '@/common/dataTime.js';
	import submit from '@/pages/imine/mine_service_submit/mine_service_submit.vue';
	import wsRequest from '@/common/websocket.js'
	import _utils from "@/common/_utils.js"
	export default {
		data() {
			return {
				friendName: "",
				msg: [
					{
						"fromId": "时光い",
						"toId": "xpq",
						"messageData": "很高兴为你服务",
						"date": "2021-12-18 20:37:03",
						"headerUrl": 'https://w.wallhaven.cc/full/rd/wallhaven-rdp987.jpg',
						"messageType": 0
					}
				],
				// 反转数据接收
				unshiftmsg: [],
				imgMsg: [],
				scrollToView: '',
				oldTime: uni.$u.timeFormat(false, 'yyyy-mm-dd hh:MM:ss'),
				inputh: '60',
				newWS: {},
				userName:''
			}
		},
		created() {
			this.userName=uni.getStorageSync('userName')
			let socketUrl = "wss://app.aixinfang.vip/message"
			this.newWS = new wsRequest(socketUrl, 5000)
			this.onMessage()
		},
		onLoad() {
			this.getHistory()
			this.initHistory()
		},
		components: {
			submit,
		},
		methods: {
			onMessage() {
				this.newWS.socketTask.onMessage((res) => {
					if (res.data != null && res.data != '') {
						let _result = JSON.parse(res.data)
						console.log(_result)
						console.log(this)
						this.friendName = _result.fromId
						this.unshiftmsg.push(_result)
					}
				})
			},
			initHistory() {
				// 数组倒叙 主要是应对后端传过来的数据
				for (var i = 0; i < this.msg.length; i++) {
					//时间间隔处理
					if (i < this.msg.length - 1) { //这里表示头部时间还是显示一下
						let t = dateTime.spaceTime(this.oldTime, this.msg[i].date);
						if (t) {
							this.oldTime = t;
						}
						this.msg[i].date = t;
					}
					// 获取图片，为下面的预览做准备
					if (this.msg[i].messageType == 1) {
						this.imgMsg.unshift(this.msg[i].messageData)
					}
					this.unshiftmsg.unshift(this.msg[i]);
				}
				// 跳转到最后一条数据 与前面的:id进行对照
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.unshiftmsg.length - 1)
				})
			},
			async getHistory() {
				let form = _utils.backTime(30)
				const data = await uni.$H.post('/webSocket/getHistoryMessage', form, {
					authCode: true,
				})
				if (data.status == 0) {
					this.msg = data.body
				} else {
					// uni.$showMsg(data.message)
					uni.$showMsg('获取历史消息失败！')
				}
			},
			changeTime(date) {
				return dateTime.dateTime1(date);
			},
			// 进行图片的预览
			previewImg(e) {
				let index = 0;
				for (let i = 0; i < this.imgMsg.length; i++) {
					if (this.imgMsg[i] == e) {
						index = i;
					}
				}
				console.log("index", index)
				// 预览图片
				uni.previewImage({
					current: index,
					urls: this.imgMsg,
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) +
								'张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			//接受输入内容
			inputs(e) {
				let _userId = uni.getStorageSync("userId")
				let _residentId = uni.getStorageSync('residentId')
				//时间间隔处理
				let data = {
					"fromId": _userId,
					"toId": this.friendName,
					"isCreateConnect": false,
					"messageData": e.message,
					"date": uni.$u.timeFormat(false, 'yyyy-mm-dd hh:MM:ss'),
					"messageType": e.type
				};
				// 发送给服务器消息
				// onSendWS(JSON.stringify(data));
				this.newWS.send(JSON.stringify(data));

				this.unshiftmsg.push(data);
				// 跳转到最后一条数据 与前面的:id进行对照
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.unshiftmsg.length - 1)
				})
				if (e.type == 1) {
					this.imgMsg.push(e.message);
				}
				console.log(e)
			},
			//输入框高度
			heights(e) {
				console.log("高度:", e)
				this.inputh = e;
				this.goBottom();
			},
			// 滚动到底部
			goBottom() {
				this.scrollToView = '';
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.unshiftmsg.length - 1)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		height: 100%;
	}

	.content {
		height: 100%;
		background-color: rgba(244, 244, 244, 1);
	}

	.chat {
		// height: 100%;
		height: 100vh;


		.chat-main {
			padding-left: 32rpx;
			padding-right: 32rpx;
			padding-top: 20rpx;
			// padding-bottom: 120rpx;  //获取动态高度
			display: flex;
			flex-direction: column;
		}

		.chat-ls {
			.chat-time {
				font-size: 24rpx;
				color: rgba(39, 40, 50, 0.3);
				line-height: 34rpx;
				padding: 10rpx 0rpx;
				text-align: center;
			}

			.msg-m {
				display: flex;
				padding: 20rpx 0;

				.user-img {
					flex: none;
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
				}

				.message {
					flex: none;
					max-width: 480rpx;
				}

				.msg-text {
					font-size: 32rpx;
					color: rgba(39, 40, 50, 1);
					line-height: 44rpx;
					padding: 18rpx 24rpx;
					word-break: break-all;
				}

				.msg-img {
					max-width: 400rpx;
					border-radius: 20rpx;
				}

			}

			.msg-left {
				flex-direction: row;

				.msg-text {
					margin-top: 30rpx;
					margin-left: 16rpx;
					background-color: #fff;
					border-radius: 0rpx 20rpx 20rpx 20rpx;
					box-shadow: 0rpx 5rpx 15rpx 0rpx rgba(0, 0, 0, 0.18);
					word-break: break-all;
				}

				.ms-img {
					margin-left: 16rpx;
				}
			}

			.msg-right {
				flex-direction: row-reverse;

				.msg-text {
					margin-top: 30rpx;
					margin-right: 16rpx;
					background-color: rgba(238, 0, 19, 1);
					border-radius: 20rpx 0rpx 20rpx 20rpx;
					color: #fff;
					// border-radius: 2rpx;
					box-shadow: 0rpx 5rpx 15rpx 0rpx rgba(0, 0, 0, 0.18);
					word-break: break-all;
				}

				.ms-img {
					margin-right: 16rpx;
				}
			}
		}
	}
	.user-name {
		margin-top: 5rpx;
		text-align: center;
		font-size: 12rpx;
		width: 60rpx;
		overflow: hidden;
		/* #ifndef APP-NVUE */
		white-space: nowrap;
		text-overflow: ellipsis;
		/* #endif */
		/* #ifdef APP-NVUE */
		lines: 1;
		text-overflow: ellipsis;
		/* #endif */
	}
</style>
